package com.hbut.job.handler;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hbut.common.core.constants.CacheConstants;
import com.hbut.common.core.constants.Constants;
import com.hbut.common.redis.service.RedisService;
import com.hbut.job.domain.Exam;
import com.hbut.job.mapper.ExamMapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class ExamXxlJob {
    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private RedisService redisService;

    @XxlJob("ExamListOrganizeHandler")
    public void ExamListOrganizeHandler() {
        //统计那些竞赛应该存入未完赛的列表中,哪些存入历史竞赛的列表中,  统计出来后在存入到对应的缓存中
        log.info("*****    ExamListOrganizeHandler    ******");
            // 查询未完成的考试列表
        List<Exam> unFinishedList = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                    .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime, Exam::getEndTime)
                    .gt(Exam::getEndTime, LocalDateTime.now()) // 结束时间大于当前时间
                    .eq(Exam::getStatus, Constants.TRUE) // 状态为有效
                    .orderByDesc(Exam::getCreateTime)); // 按创建时间降序排序
        refreshCache(unFinishedList, CacheConstants.EXAM_UNFINISHED_LIST);

            // 查询历史考试列表
        List<Exam> historyList = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                    .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime, Exam::getEndTime)
                    .le(Exam::getEndTime, LocalDateTime.now()) // 结束时间小于等于当前时间
                    .eq(Exam::getStatus, Constants.TRUE) // 状态为有效
                    .orderByDesc(Exam::getCreateTime)); // 按创建时间降序排序
        refreshCache(historyList, CacheConstants.EXAM_HISTORY_LIST);

    }


    public void refreshCache(List<Exam> examList, String examListKey) {

        // 如果考试列表为空，则直接返回
        if (CollectionUtils.isEmpty(examList)) {
            return;
        }
        // 创建一个映射，键为考试ID的字符串形式，值为对应的考试对象
        Map<String, Exam> examMap = new HashMap<>();
        // 创建一个列表，用于存储考试ID
        List<Long> examIdList = new ArrayList<>();
        // 遍历考试列表，构建映射和考试ID列表
        for (Exam exam : examList) {
            examMap.put(getDetailKey(exam.getExamId()), exam);
            examIdList.add(exam.getExamId());
        }
        // 将考试对象映射批量存储到Redis中
        redisService.multiSet(examMap);
        // 删除对应的考试列表缓存键
        redisService.deleteObject(examListKey);
        // 将考试ID列表批量推送到对应的考试列表缓存键中
        redisService.rightPushAll(examListKey, examIdList);
    }

    private String getDetailKey(Long examId) {
        return CacheConstants.EXAM_DETAIL + examId;
    }
}
